from project.models import ProjectRole, ProjectEmpower, Project, ProjectPermission
from pms.common.utils import flatten_view


def project_role_view(project_role):
    assert isinstance(project_role, ProjectRole)
    view = {
        'rid': project_role.id,
        'name': project_role.name,
        'pid': project_role.pid_id,
        'permissions': project_role_permissions(project_role)
    }
    return view


def project_role_permissions(project_role):
    assert isinstance(project_role, ProjectRole)
    permissions = [e.pid_id for e in ProjectEmpower.objects.filter(rid=project_role).order_by('pid_id')]
    permissions.sort()
    return permissions


def add_project_role(project, name):
    assert isinstance(project, Project)
    project_role = ProjectRole(name=name, pid=project)
    project_role.save()
    return project_role


def update_project_role(project_role, view):
    assert isinstance(project_role, ProjectRole)
    argv = flatten_view(view, {
        'name': 'name'
    })
    project_role.__dict__.update(**argv)
    project_role.save()
    if 'permissions' in view and view['permissions'] is not None:
        new_pids = set(view['permissions'])
        old_pids = set(project_role_permissions(project_role))
        append_pids = new_pids - old_pids
        remove_pids = old_pids - new_pids
        append_empowers = [ProjectEmpower(rid=project_role, pid=ProjectPermission.objects.get(id=pid))
                           for pid in append_pids]
        remove_empowers = [ProjectEmpower.objects.get(rid=project_role, pid=ProjectPermission.objects.get(id=pid))
                           for pid in remove_pids]
        for empower in append_empowers:
            empower.save()
        for empower in remove_empowers:
            empower.delete()
    return project_role
